<script setup>
import {onMounted, ref, watch,} from 'vue'
import {getChatInfoService,closrChat} from "@/api/user"
//获取用户聊天信息
const chatItems = ref([]);
import {getAllCategory, searchProductService} from "@/api/catalog";
import {ElMessage} from "element-plus";
//控制是登录按钮显示还是退出按钮显示
const isSignIn = inject('isSignIn')
const isSearch = inject('isSearch')
const categoryData=ref([])
const keywords=ref('');
const sendMessage=ref('')
const isAutoComplete=ref(false);
// export default {/
let token = localStorage.getItem("token");
const username = localStorage.getItem("username");
const AutoComplete=ref([]);
let ws;
import { inject } from 'vue';
import router from "@/router";




const Search=()=>{
  console.log('search'+keywords.value)
  router.push(
      {
        path:'/searchResult',
        query:{
          keywords:keywords.value
        }
      }
  )
  // let result=await searchProductService(keywords.value);
  // if(result.status===1){
  //   categoryData.value=result.data;
  //   console.log(result.data)
  // }else {
  //   alert('搜索失败');
  // }
}

const InputBlur=()=>{
  isAutoComplete.value=false;
}
const InputFocus=()=>{
  isAutoComplete.value=true;
}


const AutoKeyWords=async ()=>{
  if(keywords.value){
    isAutoComplete.value=true;
    let result=await searchProductService(keywords.value);
    if(result.status==1){
      AutoComplete.value=result.data;
      console.log(result.data);
    }
  }else {
    isAutoComplete.value=false;
  }

}

watch(
    () => keywords.value,
    (newData) => {
      console.log('newKeywords='+newData)
      AutoKeyWords();
    }
);
const init=()=> {
  token = localStorage.getItem("token");
  // localStorage.setItem("token",null);
  console.log('init token=' + token);
  if (token === 'null' || token === '' || token === null) {
    console.log("token==null")
    isSignIn.value = false;

  } else {
    console.log("token!=null")
    isSignIn.value = true;
  }
}


// ws.onmessage = function(event) {
//   chatDisplay.innerHTML = '';
//   // 处理接收到的消息
//   const msg = JSON.parse(event.data);
//   console.log('onmessage');
//
//   console.log(event.data)
//   console.log(msg);
//
//   msg.forEach(function (message) {
//     const content = message.content;
//     console.log(content)//ok,message为数组
//     const time = new Date(message.createTime).toLocaleString();
//     const userId = message.username;
//     const adminId = message.adminname;
//     const direction = message.direction;
//     const messageItem = document.createElement('li');
//     if(direction === 1){
//       messageItem.textContent = `${time}:\n${content}`;
//       messageItem.style.color = 'green';
//       messageItem.style.textAlign = 'right';
//       messageItem.style.padding = '3px';
//       messageItem.style.margin = '5px 5px 0 5px';
//       messageItem.style.whiteSpace = 'pre-wrap'; // 设置文本换行方式
//       messageItem.style.display = 'block'; // 设置每个 li 元素独占一行
//     }
//     else{
//       messageItem.textContent = `${time}\n${content}`;
//       messageItem.style.color ='blue';
//       messageItem.style.textAlign ='left';
//       messageItem.style.padding ='3px';
//       messageItem.style.margin ='5px 5px 0 5px';
//       messageItem.style.whiteSpace = 'pre-wrap'; // 设置文本换行方式
//       messageItem.style.display = 'block'; // 设置每个 li 元素独占一行
//     }
//     // messageItem.style.color = direction === 1 ? 'blue' : 'green'; // 根据方向设置消息颜色
//     // - Admin ${adminId} to User ${userId}:
//     messageItem.style.backgroundColor='white';
//     // 将消息添加到消息列表中
//     console.log(messageItem);
//     chatDisplay.appendChild(messageItem);
//   })
// };
// ws.onclose = function () {
//   console.log('close');
//   var url = `/user/closeChat`;
//   console.log("关闭的是" + username);
//   fetch(url, {
//     method: 'GET'
//   }).then(response => response.json())
//       .catch(error => {
//         console.error('请求发送失败:', error);
//       });
// }

  function signOut() {
    console.log('before  token=' + localStorage.getItem("token"))
    isSignIn.value = false;
    isSearch.value = false;
    localStorage.removeItem('token');
    token = null; // 将 token 变量也设置为 null

    ws.close();

    alert('退出登录')
    console.log('signout  token=' + localStorage.getItem("token"))
  }

  const getCategory = async () => {
    let data = await getAllCategory();
    if (data.status === 1) {
      categoryData.value = data.data;
      console.log(data.data);
    } else {
      alert('请求category失败');
    }
  }


  onMounted(() => {
    init();
    getCategory();
  });
  watch(() => isSignIn.value, (newValue) => {
    console.log("Token 值变化了：", newValue);
    init();
    if(isSignIn){
      const Url='ws://localhost:8080/chat/'+ username;
      ws=new WebSocket(Url);
      ws.onopen=()=>{
        console.log('open')
      }
      console.log('webSocket.readyState'+ws.readyState);
      ws.onclose=function () {
        console.log('close');

        var url = `/user/closeChat`;

        console.log("关闭的是"+ username);
        fetch(url,{
          method:'GET'
        }) .then(response => response.json())
            .catch(error => {
              console.error('请求发送失败:', error);
            });
      }
      // todo:改显示内容方式
      ws.onmessage = function() {
        getChatItem();

      };


    }
    // 在这里执行你想要的操作
  });

function sendMsg(){
  let time = Date.now();
  let date = new Date(time);
  // var formattedDate = date.toISOString().slice(0, 19).replace('T', ' ');

  let year = date.getFullYear();
  let month = String(date.getMonth() + 1).padStart(2, '0');
  let day = String(date.getDate()).padStart(2, '0');
  let hours = String(date.getHours()).padStart(2, '0');
  let minutes = String(date.getMinutes()).padStart(2, '0');
  let seconds = String(date.getSeconds()).padStart(2, '0');

// 构造日期时间字符串
  let formattedDate = year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
  console.log(formattedDate)
  const message = sendMessage.value;
  console.log('messageInput.value '+message)
  console.log('webSocket.readyState '+ws.readyState);
  let sendObject=JSON.stringify({
    content:message,
    createTime:formattedDate,
    username:localStorage.getItem("username"),
    adminname:"admin",
    direction:1 });
  console.log(sendObject);
  ws.send(sendObject);
  sendMessage.value = ''; // 清空输入框
  getChatItem();
}

//聊天框
  const drawer = ref(false)
  const direction = ref('rtl')
//获得历史聊天信息
  const getChatItem = async () => {
    if (token != null) {
      let result = await getChatInfoService(token);
      if (result.status === 1) {
        chatItems.value = result.data;
      } else {
        // alert("获取失败");
        ElMessage.error("获取失败")
      }
    }
  }
  getChatItem();
//关闭聊天
  const handleClose = async (done) => {
    if (token != null) {
      let result = await closrChat(token);
      if (result.status === 1) {
        done();
      } else {
        alert("error！");
      }
    }
  }
//发送聊天信息
//   const messageInput = document.getElementById('cotent');

//点击发送按钮
//   function sendMsg() {
//     let time = Date.now();
//     let date = new Date(time);
//     // var formattedDate = date.toISOString().slice(0, 19).replace('T', ' ');
//
//     let year = date.getFullYear();
//     let month = String(date.getMonth() + 1).padStart(2, '0');
//     let day = String(date.getDate()).padStart(2, '0');
//     let hours = String(date.getHours()).padStart(2, '0');
//     let minutes = String(date.getMinutes()).padStart(2, '0');
//     let seconds = String(date.getSeconds()).padStart(2, '0');
//
//     // 构造日期时间字符串
//     let formattedDate = year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
//     console.log(formattedDate)
//     const message = messageInput.value;
//     let sendObject = JSON.stringify({
//       content: message,
//       createTime: formattedDate,
//       // username:username,
//       adminname: 'admin',
//       direction: 1
//     });
//     console.log(sendObject);
//     // ws.send(sendObject);
//     messageInput.value = ''; // 清空输入框
//   }

</script>


<template>
  <div id="w">
    <div id="Header">
      <div id="Logo">
        <div id="LogoContent">
          <a href="/main"> <img src="../assets/logo-topbar.gif" /></a>
        </div>
      </div>
      <div id="Menu">
        <div id="MenuContent">
          <router-link to="/cartForm"> <a><img align="middle" name="img_cart" src="../assets/cart.gif" /></a></router-link>
          <img align="middle" src="../assets/separator.gif"  />
          <span v-if="!isSignIn">
                        <router-link to="/login" ><a>Sign In</a></router-link>
                        <img align="middle" src="../assets/separator.gif" />
                    </span>
          <span v-if="isSignIn">
                        <a @click="signOut">Sign Out</a>
                        <img align="middle" src="../assets/separator.gif" />
                        <router-link to="/myAccountFrom" >My Account</router-link>
                        <img align="middle" src="../assets/separator.gif" />

            <router-link to="/userOrders" > <a>My order</a></router-link>
                        <img align="middle" src="../assets/separator.gif" />
                    </span>
          <router-link to="/helpText">  <a>Help</a></router-link>

          <img align="middle" src="../assets/separator.gif" />
          <div id="chatContent" >
            <a @click="drawer = true"><img src="../assets/chat.png" /></a>
          </div>
        </div>
      </div>
    </div>

    <div id="QuickLinks" >
        <a class="quickLink" v-for="category in categoryData"  :key="category.catid" >
          <router-link :to="{ path: '/categoryForm', query: {category:category.catid}}">
          {{ category.catid }}
        </router-link></a>

    </div>

    <div id="Search" v-if="isSearch">
      <div id="SearchContent">

<!--        <form action="/getProductListByKey" method="get">-->
          <tr>
            <td>
              <input type="text" name="keyword" size="12" id="keyWord" placeholder="search the name" v-model="keywords"  @focus="InputFocus()">
            </td>
            <td>
              <input type="submit" name="searchProduct" value="Search" @click="Search">
            </td>
          </tr>

<!--        </form>-->
        <div id="productAutoComplete" v-if="isAutoComplete"  @mouseleave="InputBlur()">
          <ul id="productAutoList" v-for="product in AutoComplete" :key="product.productid">

            <router-link :to="{path:'/productForm',query:{productId:product.productid,category:product.name}}" style="text-decoration: none">
              <li >{{ product.productid}}:{{product.name }}</li>
            </router-link>

          </ul>
        </div>
      </div>
    </div>
  </div>





<!--  聊天框抽屉-->
  <el-drawer
      v-model="drawer"
      :direction="direction"
      :before-close="handleClose"
  >
    <template #title>
      <h2 style="font-size: 35px;color: #333333;">Chat</h2>
    </template>
    <template #default>
      <ul>
        <li>
          <span style="font-size: 18px;color: #6b778c">Hello, I'm your personal shopping assistant!</span><br>
          <span style="font-size: 18px;color: #6b778c">How can I assist you today?</span>
        </li>
      </ul>
<!--聊天框内容-->
      <ul v-for="chatItem in chatItems" :key="chatItem.id">
        <li v-if="chatItem.direction === 1" style="color: green;">
          <span>{{ chatItem.username }} to {{ chatItem.adminname }}  {{ chatItem.createTime }} </span><br>
          <span style="font-size: 18px">{{ chatItem.content }}</span>
        </li>
        <li v-if="chatItem.direction === 0" style="color: blue;">
          <span>{{ chatItem.adminname }} to {{ chatItem.username }} {{ chatItem.createTime }} </span><br>
          <span style="font-size: 18px">{{ chatItem.content }}</span>
        </li>
      </ul>

    </template>
    <template #footer>
      <div style="flex: auto">
        <el-input id="content" placeholder="Please input" style="margin: 0 10px;width: 360px" v-model="sendMessage"/>
        <el-button type="primary" @click="sendMsg()">发送</el-button>
      </div>
<!--      <div class="chat-input">-->
<!--        <input type="text" id="message-input" placeholder="请输入内容">-->
<!--        <div>-->
<!--          <button id="submitBtn" class="Button" @click="sendMsg()">发  送</button>-->
<!--        </div>-->
<!--      </div>-->
    </template>
  </el-drawer>
</template>


<style>
div#el-id-8212-17 {
  padding: 0 20px;
}
header.el-drawer__header {
  margin: 0;
}
li {
  list-style-type: none;
}
.el-drawer__header {
  align-items: center;
  color: rgb(114,118,123);
  display: flex;
  padding: var(--el-drawer-padding-primary);
  padding-bottom: 0;
}
ul{
  padding-left: 20px;
}
#w{
  background-color: #000;
  /*height:10%;*/
  margin-bottom: 0%;

}
#Logo {
  width: 50%;
  height: 10%;
  margin: 0;
  padding: 0;
  float: left;
  color: #fff;
  vertical-align:top;
}
#Menu {
  width: 50%;
  height: 10%;
  float: right;
  color: #eaac00;
  text-align: center;
}
#Menu a, #Menu a:link, #Menu a:visited, #Menu a:hover {
  margin-top: 30px;
  color: #eaac00;
  text-decoration: none;
  font-family: helvetica, tahoma, arial, verdana, sans-serif;

}
#MenuContent{
  padding-top:25px;
  padding-left: 15px;
}
#MenuContent img{
  padding: 5px;
}
#QuickLinks {
  text-align: center;
  background-color: #FFF;
  width: 100%;
  height: 30px;
  align-content: center;
}
.quickLink{
  margin-left: 10px;
}
#chatContent{

  float: right;
  padding-right: 10px;
}
.top-a{
  text-decoration: none;
  padding: 2px;
  color: black;
  font-style: italic;

}
.top-a:hover{
  text-decoration: none;
  padding: 2px;
  color: black;
  font-style: italic;
}

#Search {
  /*width: 20%;*/
  height: 10%;
  /*margin-left:35%;*/
  padding: 0;
  border-width: 0ex 0ex .3ex 0px;
  text-align: center;
  color: #eaac00;
  line-height: 9ex;
  background-color: #FFF;
}
#SearchContent{
  padding-left: 35%;
}
#Search input {
  border-width: .1ex .1ex .1ex .1ex;
  border-style: solid;
  color: #eaac00;
}
#Search input[type="text"]{
  width: 400px;
  height: 40px;
  font-size: 20px;
  border-radius: 5px;
  border: 2px solid black;
  color: black;
}
#Search input[type="text"]::placeholder{
  color: gray;
}
#Search input[type="submit"]{
  position: relative;
  width: 100px;
  height: 40px;
  /*top: -2px;*/
  border: 2px solid black;
  font-size: 18px;
  font-weight: bold;
  background: #333333;
  border-radius: 10px;
  text-align: center;
}

#productAutoList {
  margin: 0;
  padding: 0;
  border: 1px solid #aaa;
}
#productAutoList li{
  list-style: none;
  height: 25px;
  line-height: 25px;
  font-size: 13px;
  text-align: left;
  /*padding-left: 5px;*/
  /*margin-top: 3px;*/
  /*border-bottom: 1px solid #777;*/
  color: #005e21;
  cursor: pointer;
  font-weight: bold;
  margin: 0;
  padding: 0;
  border: 1px solid #aaa;
  text-decoration: none;

}
/*#productAutoComplete{*/
/*  width: 400px;*/
/*  background: #eee;*/
/*  position:relative;*/
/*  !*top: -27px;*!*/
/*  !*left: 143px;*!*/
/*}*/
#productAutoComplete{
  background: #fffffe;
  position: absolute;
  top: 179px;
  left: 597px;
  z-index: 999;
  width: 404px;
}


</style>